//
//  FHTextView+Extension.swift
//  WeiBo
//
//  Created by qfh on 16/7/21.
//  Copyright © 2016年 qiufuhe. All rights reserved.
//

import UIKit



extension FHTextView {
    
    
    var emoticonString: String? {
    
        var result = ""
        
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) -> Void in
            
            if let attachment = infoDic["NSAttachment"] as? FHTextAttachment {
            
                result += attachment.emoticon!.chs!
            } else {
            
            
                result += self.attributedText.attributedSubstringFromRange(range).string
                
            }
            
        }
    
    
    
        return result
    }



    
    func insertEmoticon(emoticon: FHEmoticon) {
    
        if emoticon.type == "0" {
            
            let originalAttributedStr = NSMutableAttributedString(attributedString: self.attributedText)
            
            
            let image = UIImage(contentsOfFile: emoticon.path!)
            
            let attachment = FHTextAttachment()
            
            attachment.emoticon = emoticon
            
            attachment.image = image
            
            let attributedStr = NSAttributedString(attachment: attachment)
            
            
            let fontHeight = self.font!.lineHeight
            
            
            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
            
            
//            originalAttributedStr.appendAttributedString(attributedStr)
            
            var range = self.selectedRange
            
            originalAttributedStr.replaceCharactersInRange(range, withAttributedString: attributedStr)
            
            
            originalAttributedStr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, originalAttributedStr.length))
            
            self.attributedText = originalAttributedStr
            
            range.location += 1
            range.length = 0
            
            self.selectedRange = range
            
            
            
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            self.delegate?.textViewDidChange?(self)
            
            
        
        } else {
        
            let emoji = (emoticon.code! as NSString ).emoji()
            
            self.insertText(emoji)
        
        }
    
    
    }





}
